import os
import random
import requests
from bs4 import BeautifulSoup
import urllib.parse
from urllib.request import urlretrieve
import time
import re

def download_random_bing_image(search_term, save_dir='./bing_images'):
    """
    从Bing图片搜索中随机下载一张图片
    
    参数:
        search_term (str): 搜索关键词
        save_dir (str): 图片保存目录，默认为'./bing_images'
    
    返回:
        str: 下载的图片本地路径，如果失败返回None
    """
    try:
        # 创建保存目录
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        
        # 构造Bing图片搜索URL
        encoded_term = urllib.parse.quote(search_term)
        url = f"https://www.bing.com/images/search?q={encoded_term}"
        
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        # 获取搜索结果页面
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        
        # 解析HTML，提取图片URL
        soup = BeautifulSoup(response.text, 'html.parser')
        img_elements = soup.find_all('img', {'class': 'mimg'})
        
        if not img_elements:
            print("未找到图片元素，尝试备用选择器...")
            img_elements = soup.find_all('img', {'src': lambda x: x and x.startswith('http')})
        
        # 过滤出有效的图片URL
        img_urls = []
        for img in img_elements:
            img_url = img.get('data-hq-src') or img.get('data-fullres-src') or img.get('src') or img.get('data-src')
            if img_url and img_url.startswith('http'):
                img_urls.append(img_url)
        
        if not img_urls:
            print("未找到任何图片URL")
            return None
        
        # 随机选择一个图片URL
        selected_url = random.choice(img_urls)
        
        # 处理URL以获取原图
        if 'th?id=' in selected_url:
            selected_url = selected_url.replace('th?id=', 'id=')
        
        # 移除尺寸和质量参数
        selected_url = re.sub(r'&w=\d+', '', selected_url)
        selected_url = re.sub(r'&h=\d+', '', selected_url)
        selected_url = re.sub(r'&qlt=\d+', '', selected_url)
        
        # 清理URL中的多余&符号
        selected_url = re.sub(r'&&+', '&', selected_url)
        selected_url = re.sub(r'&$', '', selected_url)
        
        # 生成保存路径
        timestamp = int(time.time())
        file_extension = os.path.splitext(selected_url)[1].split('?')[0]  # 处理可能带参数的URL
        if not file_extension or len(file_extension) > 5:  # 如果扩展名不存在或太长，默认.jpg
            file_extension = '.jpg'
        filename = f"bing_{search_term}_{timestamp}{file_extension}"
        save_path = os.path.join(save_dir, filename)
        
        # 下载图片
        print(f"正在下载: {selected_url}")
        urlretrieve(selected_url, save_path)
        
        print(f"图片已保存到: {save_path}")
        return save_path
    
    except Exception as e:
        print(f"发生错误: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    image_path = download_random_bing_image("风景")
    if image_path:
        print(f"下载的图片路径: {image_path}")
    else:
        print("图片下载失败")